package com.carbon.assets.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.carbon.assets.entity.*;
import com.carbon.assets.service.*;
import com.carbon.assets.vo.*;
import com.carbon.assets.common.BaseController;
import com.carbon.domain.common.ApiResult;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;

import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;


/**
 * <p>
 * 碳减排项目 前端控制器
 * </p>
 *
 * @author Li Jun
 * @since 2021-07-31
 */
@Slf4j
@RestController
@RequestMapping("/carbonProject")
@Api(value = "碳减排项目模块", tags = {"碳减排项目模块"})
public class CarbonProjectController extends BaseController {

    @Resource
    CarbonProjectService carbonProjectService;
    @Resource
    DictService dictService;
    @Resource
    CarbonMethodologyService carbonMethodologyService;
    @Resource
    CarbonResourceFileService carbonResourceFileService;
    @Resource
    CarbonMetaregistryService carbonMetaregistryService;
    @Resource
    CarbonMetaregistryProjectService  carbonMetaregistryProjectService;


    @GetMapping("/queryBySelector")
    public ApiResult queryBySelector(SelectorVo selectorVo) {


        // 2. 创建分页对象（使用Vo中的分页参数，默认第一页，每页10条）
        Page<CarbonProject> page = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(
                selectorVo.getPageNum(),
                selectorVo.getPageSize()
        );

        // 3. 调用服务层的分页查询方法
        Page<CarbonProject> resultPage =
                carbonProjectService.selectBySelector(page, selectorVo);

        // 4. 处理分页结果中的状态字典转换
        for (CarbonProject queryVo : resultPage.getRecords()) {
            String carbonMethodology = queryVo.getCarbonMethodology();
            LambdaQueryWrapper<CarbonMethodology> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CarbonMethodology::getDictCode, carbonMethodology);
            CarbonMethodology method = carbonMethodologyService.getOne(wrapper);
            queryVo.setCertificationCriteria(dictService.getDictCh(method.getCertificationCriteria()));
            queryVo.setIndustry(dictService.getDictCh(method.getIndustryCode()));
            queryVo.setProjectScope(dictService.getDictCh(queryVo.getProjectScopeCode()));
            queryVo.setProjectStatus(dictService.getDictCh(queryVo.getProjectStatus()));
            queryVo.setCarbonMethodologyName(dictService.getDictCh(method.getDictCode()));
            queryVo.setCountry(dictService.getDictCh(queryVo.getCountry()));
            queryVo.setProvince(dictService.getDictCh(queryVo.getProvince()));
        }
        // 5. 返回包含分页信息的结果
        return ApiResult.ok(resultPage);
    }


//修改时候的query，把国家省的字典查询去掉了
    @GetMapping("/queryBySelector2")
    public ApiResult queryBySelector2(SelectorVo selectorVo) {
        // 1. 验证必填参数
        if (selectorVo.getTenantId() == null || selectorVo.getTenantId().isEmpty()) {
            return ApiResult.fail("租户ID不能为空");
        }
        // 2. 创建分页对象（使用Vo中的分页参数，默认第一页，每页10条）
        Page<CarbonProject> page = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(
                selectorVo.getPageNum(),
                selectorVo.getPageSize()
        );
        // 3. 调用服务层的分页查询方法
        Page<CarbonProject> resultPage =
                carbonProjectService.selectBySelector(page, selectorVo);

        // 4. 处理分页结果中的状态字典转换
        for (CarbonProject queryVo : resultPage.getRecords()) {
            String carbonMethodology = queryVo.getCarbonMethodology();
            LambdaQueryWrapper<CarbonMethodology> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(CarbonMethodology::getDictCode, carbonMethodology);
            CarbonMethodology method = carbonMethodologyService.getOne(wrapper);

            queryVo.setCertificationCriteria(dictService.getDictCh(method.getCertificationCriteria()));
            queryVo.setIndustry(dictService.getDictCh(method.getIndustryCode()));

            queryVo.setProjectScope(dictService.getDictCh(queryVo.getProjectScopeCode()));
            queryVo.setProjectStatus(dictService.getDictCh(queryVo.getProjectStatus()));
            queryVo.setCarbonMethodologyName(dictService.getDictCh(method.getDictCode()));
//            queryVo.setCountry(dictService.getDictCh(queryVo.getCountry()));
//            queryVo.setProvince(dictService.getDictCh(queryVo.getProvince()));

        }
        // 5. 返回包含分页信息的结果
        return ApiResult.ok(resultPage);
    }


    @PostMapping("/add")
    public ApiResult add(@RequestBody CarbonProject carbonProject) {
        String methodologyCode = carbonProject.getCarbonMethodology();
        //查找项目选择方法的详细信息
        LambdaQueryWrapper<CarbonMethodology> wr = new LambdaQueryWrapper<>();
        wr.eq(CarbonMethodology::getDictCode, methodologyCode);
        CarbonMethodology methodology = carbonMethodologyService.getOne(wr);
        //给project赋值
        carbonProject.setProjectScopeCode(methodology.getFieldCode());
        carbonProject.setProjectStatus("0100000001");
        carbonProject.setCertificationCriteria(methodology.getCertificationCriteria());
        carbonProject.setIndustry(methodology.getIndustryCode());
        carbonProject.setCarbonMethodologyName(dictService.getDictCh(methodologyCode));
        carbonProjectService.save(carbonProject);
        Long id = carbonProject.getId();

        return ApiResult.ok(id);
    }


    @DeleteMapping("/delProject")
    public ApiResult delProject(@RequestParam String id) {
        boolean isDeleted = carbonProjectService.removeById(id);
        LambdaQueryWrapper<CarbonResourceFile> wr = new LambdaQueryWrapper<>();
        wr.eq(CarbonResourceFile::getProjectId, id);
        carbonResourceFileService.remove(wr);
        if (isDeleted) {
            return ApiResult.ok("成功删除");
        } else {
            return ApiResult.fail("没有该条数据");
        }
    }


    @PostMapping("/addFile")
    public ApiResult addFile(@RequestBody List<CarbonResourceFile> fileList,@RequestParam String projectId) {
        Long projectIdLong = Long.parseLong(projectId);
        for (CarbonResourceFile file : fileList) {
            file.setFileDictCode("023");
            file.setProjectId(projectIdLong );
            carbonResourceFileService.save(file);
        }
        return ApiResult.ok();
    }

    @GetMapping("/getFileList")
    public ApiResult getFileList(@RequestParam String projectId) {
        LambdaQueryWrapper<CarbonResourceFile> wr = new LambdaQueryWrapper<>();
        wr.eq(CarbonResourceFile::getProjectId,projectId);
        List<CarbonResourceFile> list = carbonResourceFileService.list(wr);
        return ApiResult.ok(list);
    }

    @PostMapping("/update")
    public ApiResult update(@RequestBody CarbonProject carbonProject) {

        Long projectId = carbonProject.getId();

        CarbonProject existingProject = carbonProjectService.getById(projectId);
        if (existingProject == null) {
            return ApiResult.fail("该项目不存在");
        }

        // 3. 如果传递了方法学编码，更新方法学相关信息
        String methodologyCode = carbonProject.getCarbonMethodology();
        if (methodologyCode != null) {
            LambdaQueryWrapper<CarbonMethodology> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(CarbonMethodology::getDictCode, methodologyCode);
            CarbonMethodology methodology = carbonMethodologyService.getOne(queryWrapper);
            if (methodology != null) {
                // 更新方法学相关字段
                carbonProject.setProjectScopeCode(methodology.getFieldCode());
                carbonProject.setCertificationCriteria(methodology.getCertificationCriteria());
                carbonProject.setIndustry(methodology.getIndustryCode());
                carbonProject.setCarbonMethodologyName(dictService.getDictCh(methodologyCode));
            } else {
                return ApiResult.fail("找不到对应的方法学信息");
            }
        }
        boolean updateSuccess = carbonProjectService.updateById(carbonProject);

        if (updateSuccess) {
            return ApiResult.ok(projectId); // 返回更新成功的项目ID
        } else {
            return ApiResult.fail("项目更新失败");
        }
    }

    @PostMapping("/updateFileList")
    public ApiResult updateFileList(@RequestBody Map<String, List> fileLists,@RequestParam String projectId) {
        for (Map.Entry<String, List> entry : fileLists.entrySet()) {
            String fileDictValue = entry.getKey(); // 获取文件类型标识
            List<Map<String, Object>> fileInfoList = entry.getValue(); // 获取该类型下的文件列表

            // 遍历每个文件信息
            for (Map<String, Object> fileInfo : fileInfoList) {
                // 创建CarbonResourceFile对象
                CarbonResourceFile carbonFile = new CarbonResourceFile();
                // 从map中提取数据并设置到对象中
                Object idObj = fileInfo.get("id");
                if (idObj != null && idObj != "") {

                    String idStr = idObj.toString().trim();
                    carbonFile.setId(Long.parseLong(idStr));
                    carbonFile.setFileName(fileInfo.get("name").toString()); // 设置文件名
                    carbonFile.setUrl(fileInfo.get("url").toString()); // 设置文件地址
                    carbonResourceFileService.updateById(carbonFile);
                }else {
                    carbonFile.setFileName(fileInfo.get("name").toString()); // 设置文件名
                    carbonFile.setUrl(fileInfo.get("url").toString()); // 设置文件地址
                    carbonFile.setFileDictValue(fileInfo.get("fileDictValue").toString());
                    Long id = Long.parseLong(projectId);
                    carbonFile.setProjectId(id);
                    carbonResourceFileService.save(carbonFile);
                }

            }
        }


        return ApiResult.ok();
    }


    @PostMapping("/addStatus")
    public ApiResult addStatus(@RequestParam String id) {
        CarbonProject carbonProject = new CarbonProject();
        carbonProject.setId(Long.parseLong(id));
        carbonProject.setProjectStatus("0100000002");
        carbonProject.setInitiationDate(new Date());
        carbonProjectService.updateById(carbonProject);
        return ApiResult.ok("立项成功");
    }

    @PostMapping("/addReduction")
    public ApiResult addReduction(@RequestBody CarbonProject carbonProject) {
        Random random = new Random();
        carbonProject.setRefId(carbonProject.getRefId());
        carbonProjectService.updateById(carbonProject);

        CarbonProject cp = carbonProjectService.getById(carbonProject.getId());

        CarbonMetaregistry carbonMetaregistry = new CarbonMetaregistry();
        carbonMetaregistry.setRefId(cp.getRefId());
        carbonMetaregistry.setProjectName(cp.getProjectName());
        carbonMetaregistry.setProjectIndustryCode(cp.getIndustry());
        carbonMetaregistry.setProjectIndustry(dictService.getDictCh(cp.getIndustry()));
        carbonMetaregistry.setProjectScopeCode(cp.getProjectScopeCode());
        carbonMetaregistry.setProjectScope(dictService.getDictCh(cp.getProjectScopeCode()));
        carbonMetaregistry.setProjectScopeTypeCode(cp.getProjectType());
        carbonMetaregistry.setProjectScopeType( dictService.getDictCh(cp.getProjectType()) );

        //记得来这里加ownerCode
        carbonMetaregistry.setProjectOwner(cp.getOwnerName());
        carbonMetaregistry.setCertifiedStandardCode(cp.getCertificationCriteria());
        carbonMetaregistry.setCertifiedStandard(dictService.getDictCh(cp.getCertificationCriteria()));
        carbonMetaregistry.setMethodologyCode(cp.getCarbonMethodology());
        carbonMetaregistry.setMethodologyName(cp.getCarbonMethodologyName());
        carbonMetaregistry.setProjectStatusCode(cp.getProjectStatus());
        carbonMetaregistry.setProjectStatus(dictService.getDictCh(cp.getProjectScopeCode()));
        carbonMetaregistry.setProjectCountryCode(cp.getCountry());
        carbonMetaregistry.setProjectProvinceCode(cp.getProvince());
        carbonMetaregistry.setProjectCity(cp.getCity());
        carbonMetaregistry.setProjectSite(cp.getAddress());
        carbonMetaregistry.setRefReduction((cp.getRecordFilingReduction()));
        carbonMetaregistry.setRemainingReduction((cp.getRecordFilingReduction()));
        carbonMetaregistry.setIssuedReduction(cp.getRecordFilingReduction());
        carbonMetaregistry.setProjectVerifierCode(cp.getCertifiedAgency());
        carbonMetaregistry.setIssuingDate(cp.getIssuingDate());
        carbonMetaregistry.setProjectVerifier(dictService.getDictCh(cp.getCertifiedAgency()));
        carbonMetaregistryService.save(carbonMetaregistry);
        Integer id = carbonMetaregistry.getId();
        CarbonMetaregistryProject carbonMetaregistryProject = new CarbonMetaregistryProject();
        carbonMetaregistryProject.setTenantId(cp.getTenantId());
        carbonMetaregistryProject.setMetaregistryId(id);
        carbonMetaregistryProjectService.save(carbonMetaregistryProject);

        return ApiResult.ok("签证审批成功");
    }
    //fetchProjectStats
    @GetMapping("/fetchProjectStats")
    public ApiResult fetchProjectStats(@RequestParam(value = "tenantId", required = true) String tenantId) {
        projectStats p  = carbonProjectService.fetchProjectStats(tenantId);
        return ApiResult.ok(p);
    }

    @GetMapping("/fetchTradeData")
    public ApiResult fetchTradeData(
            @RequestParam(required = true) Long tenantId) {
        try {
            // 调用服务层方法获取数据
            List<ProjectByType> data = carbonProjectService.fetchTradeData(tenantId);
            for (int i = 0; i < data.size(); i++) {
                data.get(i).setProjectType(dictService.getDictCh(data.get(i).getProjectType()));
            }
            // 返回成功结果（符合前端约定的code=200格式）
            return ApiResult.ok(data);
        } catch (Exception e) {
            // 异常处理：返回错误信息
            return ApiResult.fail("获取项目类型统计失败：" + e.getMessage());
        }
    }

}

